package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.qf.pojo.vo.Orders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@RestController
public class AlipayController {

    @Value("${alipay.appid}")
    private String APP_ID;

    @Value("${alipay.app_private_key}")
    private String APP_PRIVATE_KEY;

    @Value("${alipay.alipay_public_key}")
    private String ALIPAY_PUBLIC_KEY;

    @Value("${alipay.url}")
    private String url;



    @RequestMapping("/pay")
    public String pay(HttpServletRequest httpRequest, HttpServletResponse httpResponse, @RequestBody Map maps) throws IOException {
        UUID uuid = UUID.randomUUID();
        String string = uuid.toString();
        String out_trade_no = string.replace("-", "");
        //将订单存储到数据库中，并设置支付状态
        Orders orders = new Orders();
        orders.setId((Integer)maps.get("id"));
        orders.setEvaluation(out_trade_no);
        orders.setState("未支付");

        AlipayClient alipayClient =  new DefaultAlipayClient( url , APP_ID, APP_PRIVATE_KEY, "json", "utf-8", ALIPAY_PUBLIC_KEY, "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
        //同步-支付成功页面
        alipayRequest.setReturnUrl( "http://tk3fjw.natappfree.cc/#/paySuccess" );

        //异步
        alipayRequest.setNotifyUrl( "http://iwdsic.natappfree.cc/notifyUrl" ); //在公共参数中设置回跳和通知地址
        Map map = new HashMap<>();
        map.put("out_trade_no",out_trade_no);
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",Integer.valueOf(maps.get("price").toString()));
        map.put("subject",maps.get("gname"));
        map.put("body","陪玩");
        String string1 = JSONObject.toJSONString(map);
        alipayRequest.setBizContent(string1);
//        alipayRequest.setBizContent( "{"  +
//                "    \"out_trade_no\":\"201503200101010011\","  +
//                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\","  +
//                "    \"total_amount\":88.88,"  +
//                "    \"subject\":\"Iphone6 16G\","  +
//                "    \"body\":\"Iphone6 16G\","  +
//                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","  +
//                "    \"extend_params\":{"  +
//                "    \"sys_service_provider_id\":\"2088511833207846\""  +
//                "    }" +
//                "  }" ); //填充业务参数
        String form= "" ;
        try  {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
//        httpResponse.setContentType( "text/html;charset=utf-8");
//        httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();
        return form;
    }

    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws AlipayApiException {
        Map<String, String> stringStringMap = convertRequestParamsToMap(httpRequest);
        //Map<String, String> paramsMap = ... //将异步通知中收到的所有参数都存放到map中
        boolean signVerified = AlipaySignature.rsaCheckV1(stringStringMap, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2"); //调用SDK验证签名
        if(signVerified){
            System.out.println(stringStringMap);
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //得到订单号
            String out_trade_no = stringStringMap.get("out_trade_no");
            //用订单号去数据库查询订单
            //Orders orders = orderMapper.findByEvaluation(out_trade_no);
            //得到需付款的钱数
            String total_amount = stringStringMap.get("total_amount");
            String[] split = total_amount.split("[.]");
            //String[] split1 = orders.getPrice().toString().split("[.]");
            //if(split[0].equals(split1[0])){
                //订单状态为成功
              //  orders.setState("支付成功");
               //orderMapper.update(orders);
            }
        }


    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1){
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
}
